package org.jeie.gui.panels;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

import org.jeie.main.Canvas;
import org.jeie.main.Listener;

public class GUIPanel extends JPanel {
	private static final long serialVersionUID = -8461699576095094528L;

	public Canvas canvas;
	public Listener l;

	public GUIPanel(MainPanel mp) {
		setBackground(Color.gray);
		setLayout(null);

		BufferedImage img = new BufferedImage(
			128,
			128,
			BufferedImage.TYPE_INT_ARGB);
		Graphics g = img.createGraphics();
		g.setColor(Color.white);
		g.fillRect(0, 0, 128, 128);
		canvas = new Canvas(img);

		l = new Listener(mp, this, mp.toolbox);
		this.addMouseListener(l);
		this.addMouseMotionListener(l);

		canvas.setZoom(1);
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		canvas.paint(g, 10, 10);
		l.preview(g);

		if (canvas.drawGrid && canvas.getZoom() >= 8) {
			g.setXORMode(Color.black);
			int cw = canvas.getWidth() + 10;
			int ch = canvas.getHeight() + 10;
			g.setColor(Color.WHITE);
			for (int y = 10; y <= ch + 10; y += canvas.getZoom())
				g.drawLine(0, y, cw, y);
			for (int x = 10; x <= cw + 10; x += canvas.getZoom())
				g.drawLine(x, 0, x, ch);
			g.setPaintMode();
		}

		Dimension oldP = getPreferredSize();
		Dimension newP = new Dimension(
			canvas.getWidth() + 20,
			canvas.getHeight() + 20);
		if (oldP.getWidth() != newP.getWidth()
			|| oldP.getHeight() != newP.getHeight()) {
			setPreferredSize(newP);
			revalidate();
		}
	}
}
